package timeUtil

import (
	"fmt"
	"strconv"
	"strings"
	"time"
)

const (
	Second = 1
	Minute = Second * 60
	Hour   = Minute * 60
	Day    = Hour * 12
	Week   = Day * 7
	Month  = Day * 30
	Year   = Month * 12
)

// TimeStamp 获取时间戳
func TimeStamp() (s string) {
	return strconv.FormatInt(time.Now().Unix(), 10)
}

// UnixToTime 13位时间戳转时间格式1
func UnixToTime(e string) (dataTime time.Time) {
	data, _ := strconv.ParseInt(e, 10, 64)
	dataTime = time.Unix(data/1000, 0)
	return
}

// ParseWeekNum 获取一年中的第几周
func ParseWeekNum(t time.Time) int {
	var week int
	yearDay := t.YearDay()
	yearFirstDay := t.AddDate(0, 0, -yearDay+1)
	firstDayInWeek := int(yearFirstDay.Weekday())
	// 今年第一周有几天
	firstWeekDays := 1
	if firstDayInWeek != 0 {
		firstWeekDays = 7 - firstDayInWeek + 1
	}
	if yearDay <= firstWeekDays {
		week = 1
	} else {
		week = (yearDay-firstWeekDays)/7 + 2

	}
	return week
}

// GetFirstDateOfWeek 获取本周周一的日期
func GetFirstDateOfWeek() (weekStartDate time.Time) {
	now := time.Now().Local()
	offset := int(time.Monday - now.Weekday())
	if offset > 0 {
		offset = -6
	}
	weekStartDate = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
	return
}

// GetLastWeekFirstDate 获取最后一周的第一天
func GetLastWeekFirstDate() (lastWeekMonday time.Time) {
	thisWeekMonday := GetFirstDateOfWeek().Format("2006-01-02")
	TimeMonday, _ := time.Parse("2006-01-02", thisWeekMonday)
	lastWeekMonday = TimeMonday.AddDate(0, 0, -7)
	return
}

// GetFirstDateOfMouth 获取一个月的第一天
func GetFirstDateOfMouth() (mouthStartDate time.Time) {
	now := time.Now()
	mouthStartDate = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.Local)
	return
}

// ParseISO8601ToInt 解析8601时间
func ParseISO8601ToInt(durations string) (rest int, err error) {
	d, err := ParseISO8601(durations)
	if err != nil {
		return 0, err
	}
	rest = d.TS*Second + d.TM*Minute + d.TH*Hour + d.D*Day + d.W*Week + d.M*Month + d.Y*Year
	return
}

// GetLocalDayZero 获取当天零时
func GetLocalDayZero() time.Time {
	timeStr := time.Now().Format("2006-01-02")
	t, _ := time.Parse("2006-01-02", timeStr)
	return t
}

func IntToISO8601(i int) (rest string) {
	if i == 0 {
		return
	} else {
		hours := i / 3600
		days := hours / 24
		hours = hours - days*24
		minutes := i % 3600 / 60
		seconds := i % 3600 % 60
		rest = "P"
		if days != 0 {
			rest += fmt.Sprintf("%dD", days)
		}
		if hours != 0 {
			rest += "T"
			rest += fmt.Sprintf("%dH", hours)
		}
		if minutes != 0 {
			if !strings.Contains(rest, "T") {
				rest += "T"
			}
			rest += fmt.Sprintf("%dM", minutes)
		}
		if seconds != 0 {
			if !strings.Contains(rest, "T") {
				rest += "T"
			}
			rest += fmt.Sprintf("%dS", seconds)
		}
		if rest == "PT" || rest == "P" {
			rest = "PT0S"
		}
	}
	return
}
